//
//  ViewController.m
//  数据源同步_串行方法
//
//  Created by 伍银荣 on 2020/7/5.
//  Copyright © 2020 com.example. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSIndexPath *deleteIndex;

@end

@implementation ViewController

-(NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray arrayWithObjects:@"A",@"B",@"我是广告1",@"C",@"我是广告2",@"D",@"E", nil];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell_id";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.textLabel.text = self.dataArr[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.dataArr[indexPath.row] hasPrefix:@"我是广告"]) {
        return 80;
    }
    return 40;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.dataArr[indexPath.row] hasPrefix:@"我是广告"]) {
        //
        if (self.deleteIndex != nil) {
            NSLog(@"请求正在处理中,请勿操作..");
            return;
        }
        self.deleteIndex = indexPath;
        [self loadData];
    }
}

- (void)loadData {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_sync(dispatch_get_global_queue(0, 0), ^{
            [NSThread sleepForTimeInterval:2];
            NSArray *addArr = @[@"H",@"我是广告3",@"K",@"我是广告4",@"我是广告5"];
            [self.dataArr addObjectsFromArray:addArr];
            [self.dataArr removeObjectAtIndex:self.deleteIndex.row];
            self.deleteIndex = nil;
            NSLog(@"1 - 1 子线程数据请求, 预排版 ===> %@", [NSThread currentThread]);
        });
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"主线程刷新UI ===> %@", [NSThread currentThread]);
            [self.tableView reloadData];
        });
    });
}

@end
